import ROSLIB from 'roslib';
import { CMD_VEL_CANDIDATES, TWIST_MESSAGE_TYPE } from '@/constants/ros';

export function createCmdVelBinder(ros, addLog) {
  let topic = null;
  let selected = CMD_VEL_CANDIDATES[0];

  // 统一的话题创建函数
  const createTopic = (topicName) => {
    return new ROSLIB.Topic({
      ros,
      name: topicName,
      messageType: TWIST_MESSAGE_TYPE
    });
  };

  const bind = (name) => {
    selected = name || selected;
    topic = createTopic(selected);
    addLog && addLog(`✅ 已绑定cmd_vel话题: ${selected}`, 'success');
    return selected;
  };

  const detectAndBind = () => {
    if (ros && typeof ros.getTopics === 'function') {
      ros.getTopics((topicList) => {
        try {
          const all = topicList?.topics || topicList || [];
          const found = CMD_VEL_CANDIDATES.find((t) => all.includes(t));
          bind(found || CMD_VEL_CANDIDATES[0]);
        } catch {
          addLog && addLog('cmd_vel自动探测失败，使用默认: /cmd_vel', 'warning');
          bind('/cmd_vel');
        }
      }, () => {
        addLog && addLog('话题列表获取失败，使用默认: /cmd_vel', 'warning');
        bind('/cmd_vel');
      });
    } else {
      bind(CMD_VEL_CANDIDATES[0]);
    }
  };

  const publishTwist = (x, y, w) => {
    console.log('🔧 publishTwist 被调用:', { x, y, w, selected });
    
    if (!topic) {
      topic = createTopic(selected);
    }
    
    const twist = new ROSLIB.Message({
      linear: { x, y, z: 0 },
      angular: { x: 0, y: 0, z: w }
    });
    
    console.log('🔧 发布消息:', twist);
    topic.publish(twist);
    console.log(`🎮 发布速度: X=${x.toFixed(2)} Y=${y.toFixed(2)} W=${w.toFixed(2)}`);
  };

  const clear = () => { topic = null; };

  return { bind, detectAndBind, publishTwist, clear, get selected() { return selected; } };
}


